import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isNil } from 'ramda';
import { GetCategoryDto } from 'src/modules/admin/category/dto/category.dto';
import { CategoryEntity } from 'src/modules/admin/category/entities/category.entity';
import { throwHttp } from 'src/utlis';
import { Repository, Between } from 'typeorm';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private categoryEntityRepository: Repository<CategoryEntity>,
  ) { }
  async getCategory(params: GetCategoryDto, lang: string) {
    try {
      const {
        name,
        status,
        sort,
        createTimeStart,
        createTimeEnd,
      } = params;
      const where: GetCategoryDto = {
        name,
        status,
        sort,
      };
      // 创建时间筛选
      if (!isNil(createTimeStart) && !isNil(createTimeEnd)) {
        where.createDate = Between(createTimeStart, createTimeEnd);
      }
      const data = await this.categoryEntityRepository.find({
        where: {
          ...where, lang
        },
        cache: true,
        order: { createDate: 'DESC' },
      });

      return [
        {
          id: 0,
          name: '全部',
          status: 1,
          sort: 0,
          createDate: '',
          lang
        },
        ...data,
      ];
    } catch (error) {
      throwHttp(error.message);
    }
  }
}
